import express from 'express';
import {User} from '../db/model.js';
import { randomCode, sendCode } from "./getCode.js";
const router = express.Router();

router.post('/add', async (req, res) => {
    try {
        if (!req.body) {
            throw Error('没有数据')
        }
        const user = await User.findOne({account: req.body.account})
        if (user) {
            throw Error('账号已存在')
        }
        const data = await User.create(req.body)
        res.send({msg: '添加成功', code: 200, data})
    } catch (err) {
        res.send({msg: err.message, code: 500})
    }
})

router.put('/update', async (req, res) => {
    try {
        if (!req.body) {
            throw Error('没有数据')
        }
        if (!req.body._id) {
            throw Error('缺少id')
        }
        const data = await User.updateOne({_id: req._id}, req.body)
        res.status(200).send({msg: '更新成功'})
    } catch (err) {
        res.status(500).send({msg: err.message})
    }
})

router.delete('/del', async (req, res) => {
    try {
        const {_id} = req.query

        if (!_id) {
            throw Error('缺少id')
        }

        const data = await User.deleteOne({_id})
        res.status(200).send({msg: '删除成功'})
    } catch (err) {
        res.status(500).send({msg: err.message})
    }
})

router.post('/login', async (req, res) => {
    try {
        const data = await User.findOne({account: req.body.account, password: req.body.password})
            .populate('space')
            .populate('group')
            .populate({
                path:'groups.members',
            })
        if (data) {
            res.status(200).send({msg: '登录成功', code: 200, data})
        } else {
            res.status(200).send({msg: '登录失败', code: 500})
        }
    } catch (e) {
        res.status(500).send({msg: e.message})
    }
})

router.post("/getcode", (req, res) => {
    let { phone } = req.body;
    console.log(req.body);
    let code = randomCode(4); //生成6位数字随机验证码
    console.log(code);
    sendCode(phone, code, (success) => {
      if (success) {
        res.send({
          code: 200,
          codes: code,
          message: "短信验证码已发送",
        });
      } else {
        res.send({
          code: 500,
          codes: code,
          message: "短信验证码发送失败",
        });
      }
    });
  });

export default router;
